default_encoding = 'utf-8'
# coding: utf-8
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from rest_framework.decorators import api_view
import json
from myblog.models import MamahaoTestGrouping, MamahaoTestRequest
from myblog.mamahaoService.baseCode import getResonCode
from django.core import serializers
import re
import logging
import math

logger = logging.getLogger('log')


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def addGroup(request):  # 新增分组
    data = eval(json.loads(request.body)["data"])
    try:
        if (data["name"] != "" and len(data) == 3 and data["groupid"] != ""):
            group = MamahaoTestGrouping(group_name=data["name"], group_pj_id=data["groupid"], remark=data["remark"])
            group.save()
            response = getResonCode().getSuccess()
            return JsonResponse(response)
        else:
            response = getResonCode().getFail()
            response["msg"] = "缺少参数"
            return JsonResponse(response)
    except  EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


import datetime


@csrf_exempt
@api_view(['POST'])
def getGroup(request):  # 获取查询表.
    data = eval(json.loads(request.body)["data"])
    pageSize = data["pageSize"]
    pageNum = data["pageNum"]
    try:
        groupList = MamahaoTestGrouping.objects.filter(group_pj_id=data["groupid"]).order_by("-updata_time")
        gourpSizeList = groupList[:pageSize * pageNum]  # 查询数据
        gourpCount = groupList.count()  # 查询总数
        countNum = math.ceil(gourpCount / pageSize)  # 总页数
        data = json.loads(serializers.serialize("json", gourpSizeList))[
               pageSize * pageNum - pageSize:pageSize * pageNum]
        for i in range(len(data)):
            creatTime = data[i]["fields"]["creat_time"]
            updata_time = data[i]["fields"]["updata_time"]
            data[i]["fields"]["creat_time"] = re.split('[TZ.]', creatTime)[0] + " " + re.split('[TZ.]', creatTime)[1]
            data[i]["fields"]["updata_time"] = re.split('[TZ.]', updata_time)[0] + " " + re.split('[TZ.]', updata_time)[
                1]
        response = getResonCode().getSuccess()
        response["data"] = data
        response["countNum"] = countNum  # 总页数
        response["gourpCount"] = gourpCount  # 总数据量
        response["pageNum"] = pageNum  # 当前页码
        response["pageSize"] = pageSize  # 当前一页多少个数据

        return JsonResponse(response)
    except EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def updateGroup(request):  # 修改分组信息
    data = eval(json.loads(request.body)["data"])
    try:
        if data["id"] != "" and data["name"] != "":

            # MamahaoTestGrouping.objects.filter(group_id=data["id"]).update(group_name = data["name"], remark = data["remark"]) #
            Group = MamahaoTestGrouping.objects.get(group_id=data["id"])
            Group.group_name = data["name"]
            Group.remark = data["remark"]
            Group.save()
            response = getResonCode().getSuccess()
            return JsonResponse(response)
        else:
            response = getResonCode().getFail()
            response["msg"] = "缺少参数,或参数为空"
            return JsonResponse(response)
    except  EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


# MamahaoTestGrouping.objects.filter(group_id=data["id"]).update(group_name = data["name"], remark = data["remark"]) #

@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def deleteGroup(request):  # 删除分组信息
    data = eval(json.loads(request.body)["data"])
    try:
        if data["id"] != "":
            mamahaoRequest = MamahaoTestRequest.objects.filter(request_group_id=data["id"])
            if len(mamahaoRequest) > 0:
                response = getResonCode().getFail()
                response["msg"] = "当前分组模块中还存在接口用例无法删除"
                return JsonResponse(response)
            if len(mamahaoRequest) == 0:
                MamahaoTestGrouping.objects.filter(group_id=data["id"]).delete()
                response = getResonCode().getSuccess()
                response["msg"] = "删除成功"
                return JsonResponse(response)
        else:
            response = getResonCode().getFail()
            response["msg"] = "缺少参数,或参数为空"
            return JsonResponse(response)
    except  EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)
